#!/use/bin/python
# coding=utf-8
# 核心指标-经验值算法-作息时间准确率
import datetime
import pymysql
import json

from dbutils.pooled_db import PooledDB


# proactive_service_conf 数据源
def getConfConnection():
    # 开发环境
    # pool = PooledDB(pymysql, 1, host='172.20.135.96', user='pushdb', passwd='SkYWOrTh$TcOs',
    #                db='proactive_service_conf',
    #                port=3306)  # 1为连接池里的最少连接数
    # 测试环境
    pool = PooledDB(pymysql, 1, host='172.20.150.109', user='test_dmp', passwd='DghHC3lFM1KzT3ZJ',
                db='proactive_service_conf', port=3307)  # 1为连接池里的最少连接数
    # pool = PooledDB(pymysql,1,host='127.0.0.1',user='root',passwd='root',db='life_assistant_data',port=3306) # 5为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur

# proactive_service_data 数据源
def getDataConnection():
    # 开发环境
    #pool = PooledDB(pymysql, 1, host='172.20.135.96', user='pushdb', passwd='SkYWOrTh$TcOs',
    #                db='proactive_service_data',
    #                port=3306)  # 1为连接池里的最少连接数
    # 测试环境
    pool = PooledDB(pymysql, 1, host='172.20.154.103', user='test_dmp', passwd='DghHC3lFM1KzT3ZJ',
                    db='proactive_service_data', port=3407)  # 1为连接池里的最少连接数
    # pool = PooledDB(pymysql,1,host='127.0.0.1',user='root',passwd='root',db='life_assistant_data',port=3306) # 5为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur

#根据传入的SQL 返回执行SQL返回的数量
def selectNumBySql(sql,conf=2):
    if conf == 1:
        conn, cur = getConfConnection()
    else:
        conn, cur = getDataConnection()
    #print(sql)
    cur.execute(sql)
    numResult = cur.fetchone()
    num = 0
    if numResult is not None:
        num = numResult[0]
    return num

#计算百分比 保留两位小数  如:34.88%
# X为分子 Y为分母
def getRateByXY(X,Y):
    rate = 0
    if Y != 0:
        if X > Y:
            rate = 100
        else:
            rate = round(X *100 / Y, 2)
    return rate

# 记录 核心指标-经验值算法-作息时间准确率 analysis_experience_time_rate --起床时间
def insertWakeup(date):
    try:
        conn, cur = getDataConnection()
        # 获取当日 进行计算准确率的数量(预测时间和用户设置的时间同时存在的数量)
        calculateNum = selectNumBySql(f"select count(1) from proactive_service_devices t where t.prediction_wakeup_time is not null and t.wakeup_time is not null",1)
        # 获取预测时间段完全一致的数量
        equalNum = selectNumBySql(f"select count(1) from proactive_service_devices t where t.prediction_wakeup_time is not null and t.wakeup_time is not null "\
            f"and t.prediction_wakeup_time = t.wakeup_time",1)
        #计算 预测时间段10分钟内数量
        selectAccuracyNumSql = """
            select count(1) from (
select t.wakeup_time,t.prediction_wakeup_time,concat('2022-07-28 ',wakeup_time) wakeup_time_d, concat('2022-07-28 ',prediction_wakeup_time) prediction_wakeup_time_d,
unix_timestamp(STR_TO_DATE(concat('2022-07-28 ',wakeup_time),'%Y-%m-%d %H:%i:%s')) wakeup_time_t,
unix_timestamp(STR_TO_DATE(concat('2022-07-28 ',prediction_wakeup_time),'%Y-%m-%d %H:%i:%s')) prediction_wakeup_time_t
from proactive_service_devices t where t.prediction_wakeup_time is not null and t.wakeup_time is not null
and t.prediction_wakeup_time != t.wakeup_time) tt where (wakeup_time_t - prediction_wakeup_time_t) BETWEEN -600 and 600
                """
        accuracyNum = selectNumBySql(selectAccuracyNumSql,1)
        accuracyNum = accuracyNum + equalNum
        # 计算 作息时间准确度
        accuracyRate = getRateByXY(accuracyNum,calculateNum)
        logDetail = f"{date}日新增-起床时间算法准确度,有预测及实际时间数{calculateNum},完全一致数{equalNum},误差10分钟内{accuracyNum},准确率{accuracyRate}"
        print(logDetail)
        # 报表key
        analysisKey = "wakeupTimeAccuracyRate"
        saveJsonDb(analysisKey, 'wakeupTime', '起床时间', accuracyRate, date)

    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()


# 记录 核心指标-经验值算法-作息时间准确率  --睡觉时间
def insertSleep(date):
    try:
        conn, cur = getDataConnection()
        # 获取当日 进行计算准确率的数量(预测时间和用户设置的时间同时存在的数量)
        calculateNum = selectNumBySql(f"select count(1) from proactive_service_devices t where t.prediction_sleep_time is not null and t.sleep_time is not null",1)
        # 获取预测时间段完全一致的数量
        equalNum = selectNumBySql(f"select count(1) from proactive_service_devices t where t.prediction_sleep_time is not null and t.sleep_time is not null " \
            f"and t.prediction_sleep_time = t.sleep_time",1)
        #计算 预测时间段10分钟内数量
        selectAccuracyNumSql = """
            select count(1) from (
select t.sleep_time,t.prediction_sleep_time,concat('2022-07-28 ',sleep_time) sleep_time_d, concat('2022-07-28 ',prediction_sleep_time) prediction_sleep_time_d,
unix_timestamp(STR_TO_DATE(concat('2022-07-28 ',sleep_time),'%Y-%m-%d %H:%i:%s')) sleep_time_t,
unix_timestamp(STR_TO_DATE(concat('2022-07-28 ',prediction_sleep_time),'%Y-%m-%d %H:%i:%s')) prediction_sleep_time_t
from proactive_service_devices t where t.prediction_sleep_time is not null and t.sleep_time is not null
and t.prediction_sleep_time != t.sleep_time) tt where (sleep_time_t - prediction_sleep_time_t) BETWEEN -600 and 600
                """
        accuracyNum = selectNumBySql(selectAccuracyNumSql,1)
        accuracyNum = accuracyNum + equalNum
        # 计算 作息时间准确度
        accuracyRate = getRateByXY(accuracyNum, calculateNum)
        logDetail = f"{date}日新增-睡觉时间算法准确度,有预测及实际时间数{calculateNum},完全一致数{equalNum},误差10分钟内{accuracyNum},准确率{accuracyRate}"
        print(logDetail)
        # 报表key
        analysisKey = "sleepTimeAccuracyRate"
        saveJsonDb(analysisKey, 'sleepTime', '睡觉时间', accuracyRate, date)

    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()


def saveJsonDb(analysisKey,fieldKey,fieldName,fieldValue,refDate):
    try:
        conn, cur = getDataConnection()
        countNum = selectNumBySql(
            f"select count(1) from analysis_dynamic t where 1=1 and  t.ref_date = '{refDate}' and t.analysis_key = '{analysisKey}' and  JSON_EXTRACT(t.msg,'$.field_key') ='{fieldKey}'")
        msgDict = {}
        msgDict["field_key"] = fieldKey
        msgDict["field_name"] = fieldName
        msgDict["field_value"] = fieldValue
        msgJson = json.dumps(msgDict, ensure_ascii=False, sort_keys=False, separators=(',', ':'))

        if countNum == 0:
            # 插入
            insertSql = f"""insert into analysis_dynamic(analysis_key,msg,ref_date) 
                            value('{analysisKey}','{msgJson}','{refDate}')"""
            cur.execute(insertSql)
        else:
            updateSql = f"""update analysis_dynamic set msg = '{msgJson}',update_time = now()  where 1=1 and  ref_date = '{refDate}' and analysis_key = '{analysisKey}' and  JSON_EXTRACT(msg,'$.field_key') ='{fieldKey}'"""
            cur.execute(updateSql)
        conn.commit()
    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()


# 获取当前日期
def todayYMD():
    today = datetime.datetime.now()-1
    # 获取想要的日期的时间
    re_date = (today).strftime('%Y-%m-%d')
    return re_date


# 获取前1天或N天的日期，beforeOfDay=1：前1天；beforeOfDay=N：前N天
def getdate(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y-%m-%d')
    return re_date

# 获取前1天或N天的日期，beforeOfDay=1：前1天；beforeOfDay=N：前N天
def getMonthdate(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y-%m')
    return re_date


if __name__ == '__main__':
    d = 1
    date = getdate(d)
    monthdate = getMonthdate(d)
    print (f"{date} 日期,更新<动态报表-经验值算法-作息时间准确率>报表" )
    insertWakeup(date)
    insertSleep(date)

